package com.renli.controller;

import com.renli.bean.ResultJson;
import com.renli.pojo.*;
import com.renli.service.*;
import com.renli.vo.MenuVo;
import com.renli.vo.UserUpdateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Api(value = "system", tags = "系统设置")
@RestController
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserUpdateVoService userUpdateVoService;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departService;
    @Autowired
    private PostService postService;
    @Autowired
    private TitleService titleService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SalaryService salaryService;

    /**
     * 登录
     *
     * @param login
     * @return
     */
    @ApiOperation(value = "login", notes = "登录", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultJson<List<MenuVo>> login(@RequestBody @ApiParam(name = "login", value = "登录用户账号和密码", required = true) Login login) {

        ResultJson<List<MenuVo>> resultJson = new ResultJson<>();

        List<MenuVo> voList = new ArrayList<>();


        String msg = "";
        Subject subject = SecurityUtils.getSubject();
//        没有被认证
        if (!subject.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword());
            try {
                subject.login(token);
                token.setRememberMe(true);
                //                   查询所有一级菜单
                List<Permission> permissionList = permissionService.findByLogin(login);

                System.out.println(permissionList);

//                获取用户id
                Login login1 = loginService.getLogin(login.getUsername());
                Integer userId = login1.getUserId();

                permissionList.forEach(s -> {
                    MenuVo menuVo = new MenuVo();
                    menuVo.setUserId(userId);
                    menuVo.setId(s.getId());
                    menuVo.setT1(s.getName());
                    menuVo.setT2(new ArrayList<>());
                    voList.add(menuVo);
                });


                resultJson.setSuccess("登录成功", voList);
                return resultJson;
            } catch (UnknownAccountException e) {
                msg = "用户名不存在";
            } catch (AuthenticationException e) {
                msg = "用户名或密码错误";
            }
            resultJson.setSuccess(msg);
        }
        return resultJson;
    }

    /**
     * 根据用户id和菜单id
     * 查询子菜单
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "查询二级菜单", notes = "通过当前登录用户的id(userId)和点击菜单的id(menuId)来查询子菜单", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/chooseMenu", method = RequestMethod.POST)
    public ResultJson<List<MenuVo>> chooseMenu(@RequestBody @ApiParam(name = "map", value = "当前用户id和点击菜单id", required = true) Map<String, Integer> map) {

        ResultJson<List<MenuVo>> resultJson = new ResultJson<>();

        List<MenuVo> voList = new ArrayList<>();

        Integer userId = map.get("userId");
        Integer menuId = map.get("menuId");

        List<Permission> permissionList = permissionService.findPermByUserId(menuId, userId);

        MenuVo menuVo = new MenuVo();
        menuVo.setId(menuId);
        List<Map<String, String>> mapList = new ArrayList<>();
        permissionList.forEach(s -> {
            if (s.getId().equals(menuId)) {
                menuVo.setT1(s.getName());

            } else {

                Map<String, String> map1 = new LinkedHashMap<>();
                map1.put("title", s.getName());
                map1.put("url", s.getUrl());
                mapList.add(map1);
            }
        });
        menuVo.setT2(mapList);
        voList.add(menuVo);


        resultJson.setSuccess("success", voList);
        return resultJson;
    }

    /**
     * 注册账号
     *
     * @param login
     * @return
     */
    @ApiOperation(value = "注册", notes = "管理员添加账号", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public ResultJson reg(@RequestBody @ApiParam(name = "login", value = "登录的用户名和密码", required = true) Login login) {
        if (login.getPassword() == null || login.getPassword().trim().equals("")) {
            login.setPassword("666666");
        }
        SimpleHash md5 = new SimpleHash("md5", login.getPassword(), login.getUsername(), 32);
        System.out.println(md5);
        login.setPassword(md5.toString());
        if (loginService.add(login) == 1) {
//            将登录账号和个人档案资料绑定

            return new ResultJson().setSuccess("注册成功");
        } else {
            return new ResultJson().setSuccess("注册失败");
        }
    }

    /**
     * 检测账号是否存在
     *
     * @param
     * @return
     */
    @ApiOperation(value = "注册验证", notes = "检测账号是否存在", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/checkLoginExisted", method = RequestMethod.POST)
    public ResultJson checkLoginExisted(@RequestBody @ApiParam(name = "username", value = "输入用户名", required = true) Login login) {
        String username = login.getUsername();
        System.out.println(username);
        return loginService.checkName(username);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @ApiOperation(value = "退出", notes = "退出登录", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ResultJson logout() {
        return new ResultJson().setSuccess("登出成功");
    }

    /**
     * 修改用户
     * id:用户编号
     * username:用户名称
     * password：密码
     * roleId：角色id
     * depId:所属部门id
     * phone：联系电话
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "修改用户", notes = "修改用户信息", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/userUpdate", method = RequestMethod.POST)
    public ResultJson userUpdate(@RequestBody @ApiParam(name = "vo", value = "修改后信息", required = true) UserUpdateVo vo) {
        ResultJson resultJson = new ResultJson();

        userUpdateVoService.update(vo);
        return resultJson.setSuccess("执行了修改");

    }

    /**
     * 查看用户：
     * id
     * 用户名
     * 角色名
     * 部门
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "查看用户", notes = "查看用户", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/userFind", method = RequestMethod.POST)
    public ResultJson<List<UserUpdateVo>> userFind(@RequestBody UserUpdateVo vo) {

        return userUpdateVoService.find(vo);
    }

    /**
     * 查询没有账号的员工
     *
     * @return
     */
    @ApiOperation(value = "查询没有账号的员工", notes = "查询没有账号的员工", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/findNoAccount", method = RequestMethod.POST)
    public ResultJson<List<User>> findNoAccount() {
        ResultJson<List<User>> resultJson = new ResultJson<>();

        List<User> list = userService.findNoAccount();


        resultJson.setSuccess("查询成功", list);
        return resultJson;
    }


    /**
     * 新增部门
     *
     * @param dep
     * @return
     */
    @ApiOperation(value = "新增组织", notes = "新增组织", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/addDep", method = RequestMethod.POST)
    public ResultJson addDep(@RequestBody @ApiParam(name = "dep", value = "新增组织实体") Department dep) {
        return departService.add(dep);
    }

    /**
     * 删除部门
     *
     * @return
     */
    @ApiOperation(value = "删除部门", notes = "(id)删除部门", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/delDep", method = RequestMethod.POST)
    public ResultJson updateDep(@RequestBody @ApiParam(name = "depId", value = "部门id") Map<String, Integer> map) {
        Integer depId = map.get("id");
        return departService.delDep(depId);
    }

    /**
     * 查询所有部门
     *11
     * @return
     */
    @ApiOperation(value = "查询所有部门", notes = "查询所有部门", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/findAllDep", method = RequestMethod.POST)
    public ResultJson<List<Department>> findAllDep() {
        return departService.findAll();
    }

    /**
     * 添加职位
     *
     * @param post
     * @return
     */
    @ApiOperation(value = "添加职位", notes = "添加职位", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/addPost", method = RequestMethod.POST)
    public ResultJson addPost(@RequestBody @ApiParam(name = "post", value = "部门") Post post) {
        return postService.add(post);
    }

    /**
     * 分页分类
     * 查询所有职位
     *
     * @return
     */
    @ApiOperation(value = "分页分类查询所有职位", notes = "分页分类查询所有职位" +
            "id:明细id" +
            "currentPage：当前页（默认1）" +
            "pageSize：页面大小（默认6）" +
            "name：职位名称" +
            "depId：所属部门" +
            "state：是否启用（0未启用）", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/findAllPost", method = RequestMethod.POST)
    public ResultJson<List<Map<String,Object>>> findAllPost(@RequestBody(required = false) @ApiParam(name = "map", value = "查询信息") Map<String, Object> map) {

        return postService.findAll(map);
    }

    /**
     * 删除职位
     */
    @ApiOperation(value = "删除职位", notes = "根据(id)删除职位", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/delPost", method = RequestMethod.POST)
    public ResultJson delPost(@RequestBody Map<String, Integer> map) {
        Integer postId = map.get("id");
        return postService.del(postId);

    }

    /**
     * 修改职位
     *
     * @param post
     * @return
     */
    @ApiOperation(value = "修改职位", notes = "修改职位", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/updatePost", method = RequestMethod.POST)
    public ResultJson updatePost(@RequestBody Post post) {
        return postService.update(post);
    }

    /**
     * 分页分类查询所有职称
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "分页分类查询所有职称", notes = "分页分类查询所有职称" +
            "id:明细id" +
            "currentPage：当前页（默认1）" +
            "pageSize：页面大小（默认6）" +
            "name：职称名称" +
            "depId：所属部门" +
            "state：是否启用（0未启用）", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/findAllTitle", method = RequestMethod.POST)
    public ResultJson<List<Title>> findAllTitle(@RequestBody(required = false) @ApiParam(value = "查询信息") Map<String, Object> map) {
        return titleService.findAll(map);
    }


    /**
     * 添加职称
     *
     * @param title
     * @return
     */
    @ApiOperation(value = "添加职称", notes = "添加职称", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/addTitle", method = RequestMethod.POST)
    public ResultJson addTitle(@RequestBody @ApiParam(value = "添加职称信息信息") Title title) {
        return titleService.add(title);
    }

    /**
     * 根据职称id删除
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "删除职称", notes = "根据职称id(id)删除职称", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/delTitle", method = RequestMethod.POST)
    public ResultJson delTitle(@RequestBody @ApiParam(name = "map", value = "id") Map<String, Integer> map) {
        Integer id = map.get("id");
        return titleService.del(id);
    }

    /**
     * 修改职称
     *
     * @param title
     * @return
     */
    @ApiOperation(value = "职称修改", notes = "修改职称信息", httpMethod = "post",
            response = ResultJson.class)
    @RequestMapping(value = "/updateTitle", method = RequestMethod.POST)
    public ResultJson updateTitle(@RequestBody @ApiParam(name = "title", value = "职称信息") Title title) {
        return titleService.update(title);
    }

    //题库

    /*
    *  @ApiOperation(value = "分页分类查询所有职称", notes = "分页分类查询所有职称" +
            "id:明细id" +
            "currentPage：当前页（默认1）" +
            "pageSize：页面大小（默认6）" +
            "name：职称名称" +
            "depId：所属部门" +
            "state：是否启用（0未启用）", httpMethod = "post",
            response = ResultJson.class)*/

    /**
     * 分页分类查询所有试题
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "分页分类查询所有试题", notes = "分页分类查询所有职称" +
            "id：明细id" +
            "currentPage：当前页（默认1）" +
            "pageSize：页面大小（默认6）" +
            "name：试题标题" +
            "questionTypeId：试题类型id" +
            "depId：所属部门id" +
            "state：是否启用", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/findQuestion", method = RequestMethod.POST)
    public ResultJson<List<Question>> findQuestion(@RequestBody(required = false) @ApiParam(name = "map", value = "查询试题key") Map<String, Object> map) {

        return questionService.find(map);
    }

    /**
     * 新增试题
     *
     * @param question
     * @return
     */
    @ApiOperation(value = "新增试题", notes = "新增题目", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/addQuestion", method = RequestMethod.POST)
    public ResultJson addQuestion(@RequestBody @ApiParam(name = "question", value = "新增试题实体类") Question question) {
        return questionService.add(question);
    }

    /**
     * 根据id删除试题
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "根据id删除试题", notes = "删除试题", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/delQuestion", method = RequestMethod.POST)
    public ResultJson delQuestion(@RequestBody @ApiParam(name = "map", value = "删除试题id(id)") Map<String, Integer> map) {
        Integer id = map.get("id");
        return questionService.del(id);
    }

    /**
     * 跟新试题
     *
     * @param question
     * @return
     */
    @ApiOperation(value = "修改试题", notes = "修改试题", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/updateQuestion", method = RequestMethod.POST)
    public ResultJson updateQuestion(@RequestBody @ApiParam(name = "question", value = "试题跟新后数据") Question question) {
        return questionService.update(question);
    }

    @ApiOperation(value = "试题上传", notes = "上传试题文件", response = ResultJson.class)
    @RequestMapping(value = "/uploadQuestion", method = RequestMethod.POST)
    public ResultJson<String> uploadQuestion(@RequestParam("questionFile") MultipartFile upload, HttpServletRequest request) {
        System.out.println("开始上传");
        //上传路径
        String uploadFile = request.getServletContext().getRealPath("/question/");

        //获取文件名
        String fileName = upload.getOriginalFilename();
        //唯一文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        fileName = uuid + "_" + fileName;

        File file0 = new File(uploadFile);
        file0.mkdirs();

        //保存文件
        try {
            upload.transferTo(new File(uploadFile + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        ResultJson<String> resultJson = new ResultJson<>();
        resultJson.setSuccess("上传成功", fileName, 1L);

        return resultJson;
    }


    //设置角色权限


    /**
     * 查看角色列表
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "查看角色", notes = "传入查看角色的key：" +
            "description:角色描述（前台显示名称，可以不传），" +
            "currentPage：当前页（可以不传，默认1），" +
            "pageSize：每页显示行数（可以不传，默认6）", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/findRole", method = RequestMethod.POST)
    public ResultJson<List<Role>> findRole(@RequestBody(required = false) @ApiParam(name = "map", value = "查看角色信息") Map<String, Object> map) {

        return roleService.find(map);
    }

    /**
     * 查看权限
     */
    @ApiOperation(value = "查看角色权限", notes = "传入角色id（id）")
    @RequestMapping(value = "/findPerm", method = RequestMethod.POST)
    public ResultJson<List<Permission>> findPerm(@RequestBody @ApiParam(name = "map", value = "角色id") Map<String, Integer> map) {

        List<Permission> permissionList = permissionService.findByRoleId(map.get("id"));
        ResultJson<List<Permission>> resultJson = new ResultJson<>();
        resultJson.setSuccess("success", permissionList);
        return resultJson;
    }
    /**
     * 修改权限
     */
    @ApiOperation(value = "修改权限",notes = "一次修改一个")
    @RequestMapping(value = "/updatePerm",method = RequestMethod.POST)
    public ResultJson updatePerm(@RequestBody @ApiParam(name = "relperm",value = "角色id（roleId），被修改前的权限id（before），被修改后的权限id（after）") Map<String,Integer> listMap){

        return  roleService.updatePerm(listMap);
    }
    /**
     * 增加权限
     */
    @ApiOperation(value = "增加权限",notes = "一次增加一个")
    @RequestMapping(value = "/addPerm",method = RequestMethod.POST)
    public ResultJson addPerm(@RequestBody @ApiParam(name = "map",value = "角色id（roleId），权限id（permId）") Map<String,Integer> map){
        return roleService.addPerm(map);
    }
    /**
     * 删除权限
     */
    @ApiOperation(value = "删除权限",notes = "一次删除一个权限")
    @RequestMapping(value = "/delPerm",method = RequestMethod.POST)
    public ResultJson delPerm(@RequestBody @ApiParam(name = "map",value = "角色id（roleId），权限id（permId）")  Map<String ,Integer> map){
        return roleService.delPerm(map);
    }



    //工资类型

    /**
     * 分页查询所有工资类型
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "分页查询所有工资类型", notes = "接收当前页数（currentPage）和每页显示行数（pageSize），可以不传", httpMethod = "post", response = ResultJson.class)
    @RequestMapping(value = "/findAllSalary", method = RequestMethod.POST)
    public ResultJson<List<Salary>> findSalary(@RequestBody(required = false) @ApiParam(name = "map", value = "currentPage：当前页数,pageSize:每页显示行数", required = false) Map<String, Integer> map) {
        return salaryService.findAll(map);
    }

    /**
     * 批量删除工资
     *
     * @param list
     * @return
     */
    @ApiOperation(value = "批量删除工资", notes = "传入批量删除id的集合", response = ResultJson.class, httpMethod = "post")
    @RequestMapping(value = "/delSalary", method = RequestMethod.POST)
    public ResultJson delSalary(@RequestBody @ApiParam(name = "list", value = "删除工资的id集合") List<Integer> list) {
        return salaryService.del(list);
    }

    /**
     * 批量修改/新增
     */
    @ApiOperation(value = "批量修改/新增", notes = "传入工资集合数据", response = ResultJson.class, httpMethod = "post")
    @RequestMapping(value = "/updateSalary", method = RequestMethod.POST)
    public ResultJson updateSalary(@RequestBody @ApiParam(name = "list", value = "需要保存的数据", required = true) List<Salary> list) {
        return salaryService.update(list);
    }


}





















